package com.example

import android.os.Bundle
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.example.fragment.GpioPwmFragment
import com.example.fragment.SerialFragment
import com.example.fragment.I2cFragment
import com.google.android.material.navigation.NavigationView

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
    private var drawer: DrawerLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 设置Toolbar
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)

        // 初始化DrawerLayout和NavigationView
        drawer = findViewById(R.id.drawer_layout)
        val navigationView = findViewById<NavigationView>(R.id.nav_view)
        navigationView.setNavigationItemSelectedListener(this)

        // 设置ActionBarDrawerToggle
        val toggle = ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
        )
        drawer?.addDrawerListener(toggle)
        toggle.syncState()

        // 默认选中首页
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction().replace(
                R.id.main_content,
                GpioPwmFragment()
            ).commit()
            navigationView.setCheckedItem(R.id.nav_1)
        }
    }

    override fun onBackPressed() {
        if (drawer!!.isDrawerOpen(GravityCompat.START)) {
            drawer!!.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // 处理侧滑菜单项点击事件
        when (item.itemId) {
            R.id.nav_1 -> supportFragmentManager.beginTransaction().replace(
                R.id.main_content,
                GpioPwmFragment()
            ).commit()

            R.id.nav_2 -> supportFragmentManager.beginTransaction().replace(
                R.id.main_content,
                SerialFragment()
            ).commit()

            R.id.nav_3 -> supportFragmentManager.beginTransaction().replace(
                R.id.main_content,
                I2cFragment()
            ).commit()

        }

        drawer!!.closeDrawer(GravityCompat.START)
        return true
    }
}